package ee.greaton.kultuuriaken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TopicDBAdapter {
	public static final String KEY_NAME = "name";
	public static final String KEY_ID = "id";
	private static final String DATABASE_TABLE = "topics";
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_CREATE = "create table "
			+ DATABASE_TABLE + " (" + KEY_NAME + " text, " + KEY_ID + " integer);";
	private DatabaseHelper DBHelper;
	SQLiteDatabase db;

	public TopicDBAdapter(Context context) {
		DBHelper = new DatabaseHelper(context, DATABASE_TABLE,
				DATABASE_VERSION, DATABASE_CREATE);
	}

	public TopicDBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		DBHelper.close();
	}

	public void clearTopics() {
		db.delete(DATABASE_TABLE, null, null);
	}

	public void addTopic(String name, int id) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, name);
		initialValues.put(KEY_ID, id);
		db.insert(DATABASE_TABLE, null, initialValues);
	}

	public int getCount() {
		Cursor cursor = getAll();
		return cursor.getCount();
	}

	public Cursor getAll() {
		return db.query(DATABASE_TABLE, null, null, null, null, null, null);
	}
	
	public String getTopicById(int id){
		Cursor c = db.rawQuery("SELECT name FROM topics WHERE id="+id + ";", null);
		c.moveToFirst();
		return c.getString(0);
	}
	
	public void populateTopics(){
		clearTopics();
		JSONArray data;
		JSONObject c;
		JSONParser parser = new JSONParser();
		data = parser.getJSONArrayFromUrl("http://www.kultuur.info/api/topics/");
		for (int i = 0; i < data.length(); i++) {
			String name = "";
			int id = -1;
			try {
				c = data.getJSONObject(i);
				name = c.getString("name_et");
				id = c.getInt("id");
				if(id != -1){
					addTopic(name, id);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
